import 'package:hive/hive.dart';
import '../index.dart';

class MessageService {
  static const String _boxName = 'messages';

  /// 初始化消息服务
  static Future<void> initialize() async {
    // 注册适配器
    if (!Hive.isAdapterRegistered(4)) {
      Hive.registerAdapter(MessageEntityAdapter());
    }
    if (!Hive.isAdapterRegistered(5)) {
      Hive.registerAdapter(MessageTypeAdapter());
    }

    // 打开消息数据盒子
    await Hive.openBox<MessageEntity>(_boxName);

    // 初始化默认消息
    await _initializeDefaultMessages();
  }

  /// 初始化默认消息
  static Future<void> _initializeDefaultMessages() async {
    final box = Hive.box<MessageEntity>(_boxName);

    // 如果数据库为空，添加默认消息
    if (box.isEmpty) {
      for (final message in MessageEntity.defaultMessages) {
        await box.put(message.id, message);
      }
    }
  }

  /// 发送消息
  static Future<bool> sendMessage({
    required String senderId,
    required String receiverId,
    required String content,
    required MessageType type,
  }) async {
    try {
      final box = Hive.box<MessageEntity>(_boxName);

      // 生成消息ID
      final messageId = DateTime.now().millisecondsSinceEpoch.toString();

      final message = MessageEntity(
        id: messageId,
        senderId: senderId,
        receiverId: receiverId,
        content: content,
        type: type,
        timestamp: DateTime.now(),
        isRead: false,
      );

      await box.put(messageId, message);
      print('消息发送成功: $message');
      return true;
    } catch (e) {
      print('消息发送失败: $e');
      return false;
    }
  }

  /// 获取所有消息
  static List<MessageEntity> getAllMessages() {
    try {
      final box = Hive.box<MessageEntity>(_boxName);
      return box.values.toList();
    } catch (e) {
      print('获取所有消息失败: $e');
      return [];
    }
  }

  /// 根据用户ID获取该用户的所有消息（发送和接收）
  static List<MessageEntity> getMessagesByUserId(String userId) {
    try {
      final box = Hive.box<MessageEntity>(_boxName);
      return box.values
          .where(
            (message) =>
                message.senderId == userId || message.receiverId == userId,
          )
          .toList();
    } catch (e) {
      print('获取用户消息失败: $e');
      return [];
    }
  }

  /// 获取两个用户之间的对话
  static List<MessageEntity> getConversation(String userId1, String userId2) {
    try {
      final box = Hive.box<MessageEntity>(_boxName);
      final messages = box.values
          .where(
            (message) =>
                (message.senderId == userId1 &&
                    message.receiverId == userId2) ||
                (message.senderId == userId2 && message.receiverId == userId1),
          )
          .toList();

      // 按时间排序
      messages.sort((a, b) => a.timestamp.compareTo(b.timestamp));
      return messages;
    } catch (e) {
      print('获取对话失败: $e');
      return [];
    }
  }

  /// 获取用户的最新对话列表（每个对话伙伴的最后一条消息）
  static List<MessageEntity> getLatestConversations(String userId) {
    try {
      final box = Hive.box<MessageEntity>(_boxName);
      Map<String, MessageEntity> latestMessages = {};

      for (var message in box.values) {
        String partnerId;
        if (message.senderId == userId) {
          partnerId = message.receiverId;
        } else if (message.receiverId == userId) {
          partnerId = message.senderId;
        } else {
          continue; // 不是该用户的消息
        }

        if (!latestMessages.containsKey(partnerId) ||
            message.timestamp.isAfter(latestMessages[partnerId]!.timestamp)) {
          latestMessages[partnerId] = message;
        }
      }

      final result = latestMessages.values.toList();
      result.sort((a, b) => b.timestamp.compareTo(a.timestamp));
      return result;
    } catch (e) {
      print('获取最新对话列表失败: $e');
      return [];
    }
  }

  /// 获取用户的最新对话列表（过滤被举报的聊天）
  static List<MessageEntity> getLatestConversationsFiltered(String userId) {
    try {
      final currentUser = UserService.getCurrentUser();
      if (currentUser == null || currentUser.id != userId) {
        return getLatestConversations(userId);
      }

      final box = Hive.box<MessageEntity>(_boxName);
      Map<String, MessageEntity> latestMessages = {};

      for (var message in box.values) {
        String partnerId;
        if (message.senderId == userId) {
          partnerId = message.receiverId;
        } else if (message.receiverId == userId) {
          partnerId = message.senderId;
        } else {
          continue; // 不是该用户的消息
        }

        // 检查是否举报了这个聊天对象
        if (currentUser.reportedChats.contains(partnerId)) {
          continue;
        }

        // 检查是否举报了这个用户
        if (currentUser.reportedUsers.contains(partnerId)) {
          continue;
        }

        if (!latestMessages.containsKey(partnerId) ||
            message.timestamp.isAfter(latestMessages[partnerId]!.timestamp)) {
          latestMessages[partnerId] = message;
        }
      }

      final result = latestMessages.values.toList();
      result.sort((a, b) => b.timestamp.compareTo(a.timestamp));
      return result;
    } catch (e) {
      print('获取过滤后的最新对话列表失败: $e');
      return [];
    }
  }

  /// 获取未读消息数量
  static int getUnreadCount(String userId) {
    try {
      final box = Hive.box<MessageEntity>(_boxName);
      return box.values
          .where((message) => message.receiverId == userId && !message.isRead)
          .length;
    } catch (e) {
      print('获取未读消息数量失败: $e');
      return 0;
    }
  }

  /// 获取与特定伙伴的未读消息数量
  static int getUnreadCountForPartner(String userId, String partnerId) {
    try {
      final box = Hive.box<MessageEntity>(_boxName);
      return box.values
          .where(
            (message) =>
                message.senderId == partnerId &&
                message.receiverId == userId &&
                !message.isRead,
          )
          .length;
    } catch (e) {
      print('获取与特定伙伴的未读消息数量失败: $e');
      return 0;
    }
  }

  /// 标记消息为已读
  static Future<bool> markAsRead(String messageId) async {
    try {
      final box = Hive.box<MessageEntity>(_boxName);
      final message = box.get(messageId);

      if (message != null) {
        final updatedMessage = message.copyWith(isRead: true);
        await box.put(messageId, updatedMessage);
        print('消息已标记为已读: $messageId');
        return true;
      }
      return false;
    } catch (e) {
      print('标记消息已读失败: $e');
      return false;
    }
  }

  /// 标记对话中的所有消息为已读
  static Future<bool> markConversationAsRead(
    String userId,
    String partnerId,
  ) async {
    try {
      final box = Hive.box<MessageEntity>(_boxName);
      bool hasUpdates = false;

      for (var entry in box.toMap().entries) {
        final message = entry.value;
        if (message.senderId == partnerId &&
            message.receiverId == userId &&
            !message.isRead) {
          final updatedMessage = message.copyWith(isRead: true);
          await box.put(entry.key, updatedMessage);
          hasUpdates = true;
        }
      }

      if (hasUpdates) {
        print('对话消息已标记为已读: $userId <-> $partnerId');
      }
      return true;
    } catch (e) {
      print('标记对话已读失败: $e');
      return false;
    }
  }

  /// 删除消息
  static Future<bool> deleteMessage(String messageId) async {
    try {
      final box = Hive.box<MessageEntity>(_boxName);
      await box.delete(messageId);
      print('消息删除成功: $messageId');
      return true;
    } catch (e) {
      print('消息删除失败: $e');
      return false;
    }
  }

  /// 删除对话
  static Future<bool> deleteConversation(String userId1, String userId2) async {
    try {
      final box = Hive.box<MessageEntity>(_boxName);
      final messagesToDelete = <String>[];

      for (var entry in box.toMap().entries) {
        final message = entry.value;
        if ((message.senderId == userId1 && message.receiverId == userId2) ||
            (message.senderId == userId2 && message.receiverId == userId1)) {
          messagesToDelete.add(entry.key);
        }
      }

      for (var messageId in messagesToDelete) {
        await box.delete(messageId);
      }

      print('对话删除成功: $userId1 <-> $userId2');
      return true;
    } catch (e) {
      print('对话删除失败: $e');
      return false;
    }
  }

  /// 清空所有消息
  static Future<bool> clearAllMessages() async {
    try {
      final box = Hive.box<MessageEntity>(_boxName);
      await box.clear();
      print('所有消息已清空');
      return true;
    } catch (e) {
      print('清空消息失败: $e');
      return false;
    }
  }
}
